<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="问题" prop="problem">
        <el-input v-model="queryParams.problem" placeholder="请输入问题" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="是否受理">
        <el-select v-model="queryParams.isRead" placeholder="是否受理" clearable size="small">
          <el-option label="是" value="0"/>
          <el-option label="否" value="1"/>
        </el-select>
      </el-form-item>

      <el-form-item label="是否解决">
        <el-select v-model="queryParams.isComplete" placeholder="是否解决" clearable size="small">
          <el-option label="是" value="0"/>
          <el-option label="否" value="1"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['datav:workorder:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['datav:workorder:remove']">删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
       <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column label="当前问题" prop="problem" align="center" :show-overflow-tooltip="true" width="300" />
      <el-table-column label="优先级" prop="priority" align="center" :formatter="priorityFormat" width="120" />
      <el-table-column label="急速工单" prop="quickWorkOrder" :formatter="quickFormat" align="center" width="120" />
      <el-table-column label="是否受理" prop="isRead" align="center" :formatter="readFormat" width="120" />
      <el-table-column label="是否解决" prop="isComplete" align="center" :formatter="completeFormat" width="120" />
      <el-table-column label="回复内容" prop="replyContent" :show-overflow-tooltip="true" align="center" width="300" />
      <el-table-column label="创建人" prop="createBy" align="center" width="160" />
      <el-table-column label="创建时间" align="center" prop="createTime"  width="160" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-if="scope.row.isRead=='1'" v-hasPermi="['datav:workorder:edit']" >修改</el-button >
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-if="scope.row.isRead=='1'" v-hasPermi="['datav:workorder:remove']" >删除</el-button >
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row)" v-if="scope.row.isRead=='0'" v-hasPermi="['datav:workorder:view']" >查看</el-button >
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAccept(scope.row)" v-if="scope.row.isComplete=='1'" v-hasPermi="['datav:workorder:accept']" >受理</el-button >
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row)" v-if="scope.row.isComplete=='0'" v-hasPermi="['datav:workorder:check']" >详情</el-button >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="520px" append-to-body>
      <div style="height:600px;overflow-y:auto">
        <el-form ref="orderForm" :model="orderForm" :rules="rules" label-width="80px">
          <el-form-item label="当前产品" prop="product">
            <el-input v-model="orderForm.product"/>
          </el-form-item>
          <el-form-item label="当前问题" prop="problem">
            <el-input v-model="orderForm.problem" placeholder="请输入当前问题" />
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-radio-group v-model="orderForm.priority">
              <el-radio
                v-for="dict in priorityOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="急速工单" prop="quickWorkOrder">
            <el-radio-group v-model="orderForm.quickWorkOrder">
              <el-radio
                v-for="dict in quickOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="问题描述">
            <el-input v-model="orderForm.description" type="textarea" :rows="5" placeholder="请输入问题描述" ></el-input>
          </el-form-item>
          <el-form-item label="附件">
              <el-upload
              class="upload-demo"
              action
              :limit="5"
              :on-remove="removeFile"
              :http-request="httpRequest"
              :file-list="fileList" :before-upload="beforeUpload"
              multiple>
              <el-button size="small" type="primary">点击上传</el-button>
              <span>（最多上传5个文件）</span>
              </el-upload>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="orderForm.phone" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="接收短信提醒" prop="message">
            <el-radio-group v-model="orderForm.message">
              <el-radio
                v-for="dict in messageOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="orderForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="orderForm.remark" type="textarea" placeholder="请输入备注" ></el-input>
          </el-form-item>

        </el-form>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 受理工单对话框 -->
    <el-dialog :title="title" :visible.sync="workopen" width="520px" append-to-body>
      <div style="height:600px;overflow-y:auto">
        <el-form ref="workForm" :model="orderForm" :rules="rules" label-width="80px">
          <el-form-item label="当前产品" prop="product">
            <el-input v-model="orderForm.product" readonly/>
          </el-form-item>
          <el-form-item label="当前问题" prop="problem">
            <el-input v-model="orderForm.problem" placeholder="请输入当前问题" readonly/>
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-radio-group v-model="orderForm.priority" disabled>
              <el-radio
                v-for="dict in priorityOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="急速工单" prop="quickWorkOrder">
            <el-radio-group v-model="orderForm.quickWorkOrder" disabled>
              <el-radio
                v-for="dict in quickOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="问题描述">
            <el-input v-model="orderForm.description" type="textarea" :rows="5" placeholder="请输入问题描述" readonly></el-input>
          </el-form-item>
          <el-form-item label="附件">
              <div v-for="item in downloadList">
                <a :href="item.url" target="_blank" rel="noopener noreferrer">{{item.name}}</a>
              </div>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="orderForm.phone" placeholder="请输入手机号码" readonly/>
          </el-form-item>
          <el-form-item label="接收短信提醒" prop="message">
            <el-radio-group v-model="orderForm.message" disabled>
              <el-radio
                v-for="dict in messageOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="orderForm.email" placeholder="请输入邮箱" readonly/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="orderForm.remark" type="textarea" placeholder="请输入备注" readonly></el-input>
          </el-form-item>
          <el-form-item label="回复内容">
            <el-input v-model="orderForm.replyContent" type="textarea" :rows="5" placeholder="请输入回复内容" ></el-input>
          </el-form-item>

        </el-form>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitWorkForm">确 定</el-button>
        <el-button @click="cancelWork">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看工单对话框 -->
    <el-dialog :title="title" :visible.sync="viewopen" width="520px" append-to-body>
      <div style="height:600px;overflow-y:auto">
        <el-form ref="viewForm" :model="orderForm" :rules="rules" label-width="80px">
          <el-form-item label="当前产品" prop="product">
            <el-input v-model="orderForm.product" readonly/>
          </el-form-item>
          <el-form-item label="当前问题" prop="problem">
            <el-input v-model="orderForm.problem" placeholder="请输入当前问题" readonly/>
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-radio-group v-model="orderForm.priority" disabled>
              <el-radio
                v-for="dict in priorityOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="急速工单" prop="quickWorkOrder">
            <el-radio-group v-model="orderForm.quickWorkOrder" disabled>
              <el-radio
                v-for="dict in quickOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="问题描述">
            <el-input v-model="orderForm.description" type="textarea" :rows="5" placeholder="请输入问题描述" readonly></el-input>
          </el-form-item>
          <el-form-item label="附件">
              <div v-for="item in downloadList">
                <a :href="item.url" target="_blank" rel="noopener noreferrer">{{item.name}}</a>
              </div>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="orderForm.phone" placeholder="请输入手机号码" readonly/>
          </el-form-item>
          <el-form-item label="接收短信提醒" prop="message">
            <el-radio-group v-model="orderForm.message" disabled>
              <el-radio
                v-for="dict in messageOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="orderForm.email" placeholder="请输入邮箱" readonly/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="orderForm.remark" type="textarea" placeholder="请输入备注" readonly></el-input>
          </el-form-item>
          <el-form-item label="回复内容">
            <el-input v-model="orderForm.replyContent" type="textarea" :rows="5" placeholder="请输入回复内容" ></el-input>
          </el-form-item>

        </el-form>
      </div>
      
    </el-dialog>
  </div>
</template>

<script>
import { listWorkorder, getWorkorder, addWorkorder, updateWorkorder, delWorkorder,acceptWorkorder,completeWorkorder,delFile} from "@/api/tool/datav/order";
import { getUser} from "@/api/system/user";
import FileSaver from "file-saver";
import CHAT from "./util/netty";
import Vue from 'vue';
Vue.use(CHAT);
export default {
  name: "WorkOrder",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        problem: undefined,
        isRead: undefined,
        isComplete: undefined,
      },
      // 表单参数
      orderForm: {
        product:'智慧数据大屏',
        priority: "1",
        quickWorkOrder: "1",
        message: "0",
		  },
      fileList:[],
      uploadList:[],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        product: [
          { required: true, message: "当前产品不能为空", trigger: "blur" }
        ],
        problem: [
          { required: true, message: "当前问题不能为空", trigger: "blur" }
        ],
       
      },
      //优先级字典数据
      priorityOptions:[],
      //急速工单字典数据
      quickOptions:[],
      //受理字典数据
      readOptions:[],
      //解决字典数据
      completeOptions:[],
      //短信状态字典数据
      messageOptions:[],
      //受理工单页面显示情况
      workopen: false,
      //文件下载列表
      downloadList:[],
      //查看工单显示情况
      viewopen: false
    };
  },
  created() {
    this.getList();
    this.getDicts("priority").then(response => {
      this.priorityOptions = response.data;
    });
    this.getDicts("quick_work_order").then(response => {
      this.quickOptions = response.data;
    });
    this.getDicts("is_read").then(response => {
      this.readOptions = response.data;
    });
    this.getDicts("is_complete").then(response => {
      this.completeOptions = response.data;
    });
    this.getDicts("message").then(response => {
      this.messageOptions = response.data;
    });
  },
  methods: {
    /** 查询数据源列表 */
    getList() {
      this.loading = true;
      listWorkorder(this.queryParams).then((response) => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 优先级状态字典翻译
    priorityFormat(row, column) {
      return this.selectDictLabel(this.priorityOptions, row.priority);
    },
    // 急速工单字典翻译
    quickFormat(row, column) {
      return this.selectDictLabel(this.quickOptions, row.quickWorkOrder);
    },
    // 受理状态字典翻译
    readFormat(row, column) {
      return this.selectDictLabel(this.readOptions, row.isRead);
    },
    // 解决状态字典翻译
    completeFormat(row, column) {
      return this.selectDictLabel(this.completeOptions, row.isComplete);
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.fileList = [];
      this.uploadList = [];
      this.downloadList = [],
      this.orderForm = {      
        product:'智慧数据大屏',
        priority: "1",
        quickWorkOrder: "1",
        message: "0",
        problem: undefined,
        description: undefined,
        phone: undefined,
        email: undefined,
        remark: undefined,
        replyContent: undefined,
      };
      this.resetForm("orderForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      //this.dateRange = [];
      this.queryParams.isRead = undefined;
      this.queryParams.isComplete = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      //   this.$nextTick(() => {
      //     this.getRoleMenuTreeselect(roleId);
      //   });
      getWorkorder(id).then((response) => {
      
        this.orderForm = response.data;
        if(response.data.enclosure != null && response.data.enclosure != ""){
          let files = response.data.enclosure.split(",");
          files.pop();
          for(let i =0;i<files.length;i++) {
            
            this.fileList.push({"name":"附件"+(i+1),"url":files[i]})
          }
        }
        this.open = true;
        this.title = "修改工单";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["orderForm"].validate((valid) => {
        if (valid) {
           // 使用form表单的数据格式
          let paramsData = new FormData()
          // 将上传文件数组依次添加到参数paramsData中
          this.uploadList.forEach((it, index) => {
            paramsData.append('file', it.file); // 因为要上传多个文件，所以需要遍历一下才行
          });
          // 将表单数据添加到参数paramsData中
          paramsData.append('id', this.orderForm.id)
          paramsData.append('product', this.orderForm.product ? this.orderForm.product : '')
          paramsData.append('problem', this.orderForm.problem ? this.orderForm.problem : '')
          paramsData.append('priority', this.orderForm.priority)
          paramsData.append('quickWorkOrder', this.orderForm.quickWorkOrder)
          paramsData.append('description', this.orderForm.description ? this.orderForm.description : '')
          paramsData.append('phone', this.orderForm.phone ? this.orderForm.phone : '')
          paramsData.append('message', this.orderForm.message ? this.orderForm.message : '')
          paramsData.append('email', this.orderForm.email ? this.orderForm.email : '')
          paramsData.append('enclosure', this.orderForm.enclosure)
          paramsData.append('remark', this.orderForm.remark ? this.orderForm.remark : '')
          paramsData.append('replyContent', this.orderForm.replyContent ? this.orderForm.replyContent : '')

          if (this.orderForm.id != undefined) {
            updateWorkorder(paramsData).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.uploadList = [];
                this.fileList = [];
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addWorkorder(paramsData).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.uploadList = [];
                this.fileList = [];
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除序号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(function () {
          return delWorkorder(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {});
    },
     // 上传预处理
    beforeUpload(file) {
       const isLt10M = file.size / 1024 / 1024  < 20;
        if (!isLt10M) {
            this.$message.error('上传文件大小不能超过20MB哦!');
            return false;
        }
    },
    //自定义上传,重写文件上传方法,覆盖原有的上传方法，将上传的文件依次添加到fileList数组中
    httpRequest(option) {
        this.uploadList.push(option);
        this.msgSuccess("成功上传至浏览器缓存");
    },
    removeFile(file, fileList){
      this.uploadList = fileList

      if(file.url != ""){
        //在服务器中删除文件
        delFile(file.url).then(response => {
          if (response.code === 200) {
            //在表单附件列表中删除文件地址
            let list = this.orderForm.enclosure.split(",");
            for(let i=0;i<list.length;i++)
              if(list[i] == file.url){
                list.splice(i,1)
              }
              this.orderForm.enclosure = list.join(",")
           
          }         
        })
      }
    },
    handleAccept(row){
      this.resetWorkForm();
      const id = row.id || this.ids;
      //   this.$nextTick(() => {
      //     this.getRoleMenuTreeselect(roleId);
      //   });
      this.orderForm.id = id;
      if(row.isRead == "1"){
        acceptWorkorder(this.orderForm).then((response) => {
          if (response.code === 200) {
          
          } else {
            this.msgError(response.msg);
          }
        });
      }
      getWorkorder(id).then((response) => {
      
        this.orderForm = response.data;
        if(response.data.enclosure != null && response.data.enclosure != ""){
          let files = response.data.enclosure.split(",");
          files.pop();
          for(let i =0;i<files.length;i++) {
            
            this.downloadList.push({"name":"附件"+(i+1),"url":files[i]})
          }
        }
        this.workopen = true;
        this.title = "受理工单";
      });

      
    },
    resetWorkForm(){
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.fileList = [];
      this.uploadList = [];
      this.downloadList = [],
      this.orderForm = {      
        product:'智慧数据大屏',
        priority: "1",
        quickWorkOrder: "1",
        message: "0",
        problem: undefined,
        description: undefined,
        phone: undefined,
        email: undefined,
        remark: undefined,
        replyContent: undefined,
      };
      this.resetForm("workForm");
    },
    submitWorkForm(){
      completeWorkorder(this.orderForm).then((response) => {
        if (response.code === 200) {
            this.msgSuccess("已解决");
            this.workopen = false;
            this.downloadList = [];
            this.getList();
          } else {
            this.msgError(response.msg);
          }
        });
    },
    cancelWork(){
      this.workopen = false;
      this.resetWorkForm();
    },
    handleView(row){
      
      this.reset();
      const id = row.id || this.ids;
      //   this.$nextTick(() => {
      //     this.getRoleMenuTreeselect(roleId);
      //   });
      getWorkorder(id).then((response) => {
      
        this.orderForm = response.data;
        if(response.data.enclosure != null && response.data.enclosure != ""){
          let files = response.data.enclosure.split(",");
          files.pop();
          for(let i =0;i<files.length;i++) {
            
            this.downloadList.push({"name":"附件"+(i+1),"url":files[i]})
          }
        }
        this.viewopen = true;
        this.title = "工单详情";
      });
    }
  },
};
</script>
<style scoped>
/**  滚动条凹槽的颜色，还可以设置边框属性  **/
::-webkit-scrollbar-track-piece { 

  background-color:#f8f8f8; 
  border-radius: 10px;
}
/** 滚动条的宽度  **/
::-webkit-scrollbar {

  width:9px;

  height:9px; 

}
/** 滚动条的设置  **/
::-webkit-scrollbar-thumb {

  background-color:#dddddd;

  background-clip:padding-box;

  min-height:28px; 
  border-radius: 10px;

}

::-webkit-scrollbar-thumb:hover {

  background-color:#bbb; 

}
</style>